class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  skip_before_filter :verify_authenticity_token
  # http_basic_authenticate_with name: "admin", password: "admin123"

  before_action :require_login

  def require_login
    unless current_user
      redirect_to login_url
    end
  end

  helper_method :current_user
  helper_method :audited_script

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def audited_script
    @audited ||= SqlOrder.find(params[:id]) unless !params[:id]
  end

  def show_app
    @show_app ||= App.find(params[:id]) unless !params[:id]
  end

  def require_login
    redirect_to '/login' unless current_user
  end

  def require_deploy_predepoloy
    redirect_to '/' unless current_user.can_deploy_predeploy?
  end

  def require_deploy_production
    redirect_to '/' unless current_user.can_deploy_production?
  end

  def require_sql_audit
    redirect_to '/' unless current_user.can_admin_leader?
  end

  def require_audited
    redirect_to '/' unless audited_script.can_audited?
  end

  helper_method :is_deploy_time?

  #是否在上线时间窗内
  def is_deploy_time?
    now = Time.now()
    if ((11..13) === now.hour || (17..20) === now.hour)
      return false
    else
      return true
    end
  end

  def check_sql(orderid)
    Thread.new {
      begin
        ret = nil
        order = SqlOrder.find(orderid)
        order.done_entries = 0
        order.all_entries = 0
        order.save
        DaemonLogger.logger.info("SqlCheck: Order:#{orderid}, script called: #{order.title}.")
        begin_time = nil
        Timeout::timeout(600) do
          ret = system('if [ ! -x scripts/parse_query.py ]; then chmod +x scripts/parse_query.py; fi')
          begin_time = Time.now
          ret = system("scripts/parse_query.py #{orderid}")
        end
        if ret
          interval = (Time.now - begin_time).to_i
          DaemonLogger.logger.info("SqlCheck: Order:#{orderid}: check succeeded.")
          DaemonLogger.logger.info("SqlCheck: Order:#{orderid}: script check during #{interval/60}m:#{interval%60}s.")
        else
          DaemonLogger.logger.error("SqlCheck: Order:#{orderid}: pase_query.py exit error")
        end
      rescue => e
        DaemonLogger.logger.error("SqlCheck: Order:#{orderid}: check error, reason:#{e.message}.")
      ensure
        ActiveRecord::Base.connection_pool.release_connection
      end
    }
  end

  def check_file(fileid)
    DaemonLogger.logger.info("upload file contents to databases: Order:#{fileid}.")
    system('if [ ! -x scripts/file_upload.py ]; then chmod +x scripts/file_upload.py; fi')
    system("scripts/file_upload.py #{fileid}")
    check_sql(fileid)
  end

  
end
